<!DOCTYPE html>
<html>
	<head>
		<title>烟草种子发芽检测与计数</title>
		{% load static %}
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<link rel="shortcut icon" href="{% static 'img/seed.ico'%}" type="image/x-icon" />

		<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
		<script src="{% static 'js/jquery-3.6.0.min.js' %}"></script>
		<script src="{% static 'js/popper.min.js' %}"></script>
		<script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
		<script src="{% static 'js/axios.min.js' %}"></script>

		<style>
			.custom-file-input~.custom-file-label::after {
				content: "选择图片";
			}

			.custom-control-input:checked~.custom-control-label::before {
				background-color: #28a745;
				border-color: #28a745;
			}

			.floatBox {
				position: absolute;
				box-sizing: content-box;
				display: block;
				border: 3px solid black;
				opacity: 35%;
				background-color: burlywood;
				z-index: 150;
			}

			.floatBox:hover {
				opacity: 40%;
				background-color: blue;
				border-width: 4px dashed;
			}

			.myCenterText {
				padding-left: 4px !important;
				padding-right: 4px !important;
			}
			.input-group {flex-wrap: nowrap;	}
			/* * /
			#detect form  div.input-group  div.input-group {flex-wrap: nowrap;	}
			/*	*/
		</style>
	</head>
	<body>

		<div class="container">
			<!--	<h4>烟草种子发芽图片检测</h4>-->
			<nav class="navbar navbar-expand-sm bg-light">
				<ul class="nav nav-tabs" role="tablist">
					<li class="nav-item" role="presentation">
						<a role="tab" class="nav-link" data-toggle="tab" href="#home" id="a_home">上传图片</a>
					</li>
					<li class="nav-item" role="presentation">
						<a role="tab" class="nav-link" data-toggle="tab" href="#detect" id="a_detect">检测结果</a>
					</li>
					<li class="nav-item" style="display: none;" role="presentation">
						<a role="tab" class="nav-link" data-toggle="tab" href="#custom" id="a_custom">自定义</a>
					</li>
				</ul>
			</nav>

			<!-- Tab panes -->
			<div class="tab-content mb-3">
				<div id="home" class="tab-pane active" role="tabpanel"><br>
					<div id="main" class="main">

						<form method="post" enctype="multipart/form-data" action="../upload2/" id="myForm">
							{% csrf_token %}

							<button type="button" id="capture" class="btn btn-primary mb-2 mr-3">种子拍照</button>
							<button type="button" id="localFile" class="btn btn-primary mb-2 mr-3">本地图片</button>
							<button type="button" id="uploadAjax" class="btn btn-success mb-2 mr-3">种子检测</button>
							<div id="choseAction" style="display:block;">
								<input name="action" value="form" type="radio" />form
								<input name="action" value="ajax" type="radio" checked="checked" />ajax
								<input name="action" value="test" type="radio" />test
							</div>

							<div class="custom-file mb-3 col-md-6" style="display:none;">
								<input id="file" type="file" accept="image/*" class="custom-file-input" />
								<label class="custom-file-label" for="file">上传文件</label>
							</div>

							<div class="progress" style="display:none">
								<div id="uploadProgress" class="progress-bar progress-bar-striped progress-bar-animated"
									style="width:1%">1%
								</div>
							</div>
							<div>
								<button type="submit" id="upload" class="btn btn-primary" style="display:none;">提交表单识别
								</button>
							</div>
						</form>
						<div id="spinner" style="display:none;">
							<div class="spinner-border text-primary"></div>
							显示图片中...
						</div>
						<div id="pending" style="display:none;">
							<div class="spinner-border text-primary"></div>
							检测种子中...
						</div>

						<div class="alert alert-success alert-dismissible">
							<button type="button" class="close" data-dismiss="alert">&times;</button>
							<strong>提示：</strong>上传图片的最大的边长要确保在<span style="color:red">3400~5000</span>像素之间，以保证足够的准确率。
						</div>


					</div>
				</div>

				<div id="detect" class="tab-pane fade" role="tabpanel"><br>
					<div class="main" id="result">
						<form>
							<div class="mb-2">
								<span id="msgResult">检测结果：</span>
								<button type="button" id="btn_copy" class="btn btn-primary">数据复制</button>

								<!--                        <div class="custom-control custom-checkbox">-->
								<!--                            <input type="checkbox" class="custom-control-input" id="customSwitch1" checked>-->
								<!--                            <label class="custom-control-label" for="customSwitch1">网球</label>-->
								<!--                        </div>-->
								<div class="custom-control  custom-switch ml-2" style="display:inline-block;">
									<input type="checkbox" class="custom-control-input" id="labelNumber">
									<label class="custom-control-label" for="labelNumber">种子序号</label>
								</div>
								<div class="custom-control  custom-switch ml-2" style="display:inline-block;">
									<input type="checkbox" class="custom-control-input" id="labelShow">
									<label class="custom-control-label" for="labelShow">检测框</label>
								</div>
								
								<button type="button" id="drawRect" class="btn btn-primary" style="display: none;">画出检测框
								</button>
								<!-- <button class="btn btn-info">重置</button> -->
							</div>
							<div class="input-group">
								<div class="input-group-prepend">
									<span class="input-group-text">　发芽种子数量</span>
								</div>
								<input type="number" id="health" value="0"
									class="myCenterText form-control col-md-4 col-sm-6" min="0" step="1" />
							</div>
							<div class="input-group">
								<div class="input-group-prepend">
									<span class="input-group-text">　单叶种子数量</span>
								</div>
								<input type="number" min="0" step="1" id="oneleaf" value="0"
									class="myCenterText form-control col-md-4 col-sm-6" />
							</div>
							<div class="input-group">
								<div class="input-group-prepend">
									<span class="input-group-text">不确定种子数量</span>
								</div>
								<input type="number" min="0" step="1" id="partial" value="0"
									class="myCenterText form-control col-md-4 col-sm-6" />
							</div>
							<div class="input-group" style="display:none;">
								<div class="input-group-prepend">
									<span class="input-group-text">检测种子总数量</span>
								</div>
								<input type="number" min="0" step="1" id="seeds" value="0"
									class="myCenterText form-control col-md-4 col-sm-6" disabled />
							</div>
							<p><img src="" class="img-fluid" id="showImg" style="display:none;" /></p>
						</form>
						<textarea id="copy_data" style="opacity: 0;position: absolute;"></textarea>

						<div class="alert alert-info alert-dismissible" style="display: none;" id="alertServer">
							<button type="button" class="close" data-dismiss="alert">&times;</button>
							<strong>注意：</strong>服务器正在维护中，目前只能对预设检测结果进行操作。
						</div>
						<div class="alert alert-success alert-dismissible" style="display: none;" id="alertShow">
							<button type="button" class="close" data-dismiss="alert">&times;</button>
							<strong>提示：</strong>长按下方检测框，选中框后再点击一次，可修改结果。
						</div>
					</div>
				</div>

				<div id="custom" class="container tab-pane fade" role="tabpanel"><br>
					<h3>Menu 2</h3>
				</div>
			</div>

			<div id="boxesDiv" style="position:relative;border:0px solid black;padding:0px;" class="clearfix">
				<canvas id="show" class="img-fluid" style="position:absolute;top:0px;left:0px;z-index:0;"></canvas>
				<canvas id="showBox" class="img-fluid" style="position:absolute;top:0px;left:0px;z-index:100;"></canvas>

				<div class="dropdown-menu" id="menu" style="z-index:200;">
					<a class="dropdown-item" href="javascript:void(0)">设置为发芽种子</a>
					<a class="dropdown-item" href="javascript:void(0)">设置为单叶种子</a>
					<a class="dropdown-item" href="javascript:void(0)">设置为不确定</a>
					<a class="dropdown-item" href="javascript:void(0)">设置为不是种子</a>
					<a class="dropdown-item" href="javascript:void(0)" style="color:blue;">不做修改，退出菜单</a>
				</div>
			</div>
		</div>
		<script>
			$(function() {
				$('[data-toggle="popover"]').popover();

				let $btnCopy = document.querySelector("#btn_copy"); //上传识别按钮
				$btnCopy.onclick = copyToClipboard;


				let $submit = document.querySelector("#upload"); //上传识别按钮
				$submit.onclick = function() {
					let form = document.querySelector("#myForm");
					form.submit();
				};

				//Ajax异步提交种子图片，并显示结果
				let btnn = document.querySelector('#uploadAjax');
				btnn.onclick = function() {
					//console.log('uploadAjax');
					let csrf = $('#myForm input[name="csrfmiddlewaretoken"]').val();
					let $form = document.querySelector('#myForm');

					let usize = 0
					try {
						usize = $form.file.files[0].size;
						if (usize <= 0)
							throw ('文件大小为0！')
					} catch (e) {
						bootbox.alert({
							title: "错误",
							message: "请选择图片后上传！",
							size: 'small'
						});
						return; //错误退出
					}

					//let action = 'test';//'ajax';// 'form';//'ajax  测试用
					let action = $('#choseAction input[name="action"]:checked').val();
					console.log(action);

					let dataForm = new FormData()
					dataForm.append('csrfmiddlewaretoken', csrf)
					dataForm.append('file', $form.file.files[0]);
					dataForm.append('action', action);
					
					let $canvas = document.querySelector("#show");
					dataForm.append('width', $canvas.width);
					dataForm.append('height', $canvas.height); //增加原始尺寸传递

					axios.post("../upload2/", //访问后台
							dataForm, {
								headers: {
									"Content-Type": "multipart/form-data"
								},
								onUploadProgress: function(progressEvent) {
									let complete = parseInt((progressEvent.loaded / progressEvent.total) * 100)
									if (complete % 10 != 0)
										return;

									let text = complete + '%';
									$('#uploadProgress').css('width', text).text(text).parent().show();
									if (complete == 100) {
										$('#uploadProgress').parent().hide(500);
										$('#pending').show();
									}

									console.log(complete);
								},
							})
						.then(function(response) { //结果显示操作
							let result = response.data;

							if (action == 'ajax') {//实际用
								showData(result); //显示检测结果
								window.g_data = result; //保存全局变量，复杂的JSON对象
							} else if (action == 'test') {// 测试用
								document.querySelector('#alertServer').style.display = '';
								let url = "{% static 'seed_71.jpg' %}"
								showImageSrcInCanvas(url); //还要在里面设置 showData,主要考虑异步		

								showData(result); //显示检测结果
								window.g_data = result; //保存全局变量，复杂的JSON对象
							} else {
								document.querySelector('#result').innerHTML = result; //form，直接显示网页结果
							}

							$('#a_detect').tab('show');
							$('#pending').hide(); //检测过程提示

							document.querySelector('#showDialog').click(); //显示对话框

							document.querySelector('#drawRect').click(); //触发显示图片与boxes
							document.querySelector('#alertShow').style.display = ''; //显示提示
							document.querySelector("#labelNumber").checked = false;
							document.querySelector("#labelShow").checked = true;
						})
						.catch(function(error) {
							bootbox.alert({
								title: "错误",
								message: "有未知错误，请刷新后重试",
								size: 'small'
							});
							console.log(error);
						});
				};

				const $camera = document.querySelector("#file");
				$camera.onchange = handleTakePhoto; //文件上传或手机拍照

				document.querySelector("#capture").onclick = function() {
					// 部分机型默认设置会不生效，需要手动再赋值
					$camera.setAttribute("capture", "user");
					$camera.click();
				}

				document.querySelector("#localFile").onclick = function() {
					// 部分机型默认设置会不生效，需要手动再赋值
					$camera.removeAttribute("capture");
					$camera.click();
				}

				//画出 boxes函数
				document.querySelector('#drawRect').onclick = function() {
					if (window.g_data) // 这里有问题  
						showBoxesInCanvas(); //画出boxes
					else
						console.log('no g_data');
				}

				///*
				//长按/单击的时间
				// if (isMobileDevice() == true) {
				$('#showBox').on({
					touchstart: function(e) {
						console.log('touchstart: X=', e.originalEvent.touches[0].clientX, '\tY=', e
							.originalEvent.touches[0].clientY);
						tid = setTimeout(c, 70, e); //(e); //触发长按事件
						//e.preventDefault();
					},
					touchmove: function(e) {
						clearTimeout(tid);
						tid = 0;
					},
					touchend: function(e) {
						clearTimeout(tid);
						return false;
					}
				});
				// } else {
				//*/

				document.querySelector("#showBox").addEventListener('mousedown', doShowDiv); //触发长按事件
				// }
				//*/

				//设置弹出菜单的选项的点击事件
				$('#menu a').each(function(index, dom) {
					var msg = ["确定修改为发芽种子?", "确定修改为单叶种子?", "确定修改为不确定种子?", "确定修改为不是种子?", "不做修改，退出菜单！"];

					$(this).on('click', function() {
						if (index == 4) {
							setTimeout(removeCurrentDiv, 1200); //必须等一会再去除
							return; //直接退出	
						}

						bootbox.confirm({
							size: "small",
							message: msg[index],
							title: "修改结果",
							callback: function(result) {
								console.log(index + ":" + result);
								if (result == true) {
									try {
										var div = window.saveDiv;

										let label = div.getAttribute('my_label');
										let ii = div.getAttribute('my_index');

										setSeedLabel(index, ii); //设置种子检测结果变化
									} catch (e) {
										console.log(e);
									}
								}
								removeCurrentDiv();
							}
						});
					});
				});

				$('#health, #oneleaf').on('change', function() { //触发种子数量的 更新
					let arr = getInputDataArray();
					let seeds = arr[0] + arr[1];
					$('#seeds').val(seeds).trigger('change');
				})
				$('#a_home').tab('show');

				document.querySelector("#labelNumber").onclick = function() {
					if (!window.g_data)
						return;

					if (this.checked == true) {
						const $canvas = document.querySelector("#showBox");
						let ctx = $canvas.getContext("2d");
						labelSeedNumbers(ctx);
					} else {
						showBoxesInCanvas();
					}
				}
				document.querySelector("#labelShow").onclick = function() {
					if (!window.g_data)
						return;

					if (this.checked == true) {
						showBoxesInCanvas();
					} else {
						removeBoxes();
					}
				}

			});
		</script>
		<script>
			//由点击事件来设置种子的新属性
			function setSeedLabel(newLabel, ii) {
				if (!window.g_data) {
					console.log('没有数据');
					return;
				}

				let boxes = window.g_data.boxes;
				let box = boxes[ii];
				let oldLabel = box[0];

				if (oldLabel == newLabel) {
					bootbox.alert({
						title: "提示",
						message: "种子检测结果没有改!",
						size: 'small'
					});
					return;
				}

				box[0] = newLabel;
				let arr = getInputDataArray();

				arr[oldLabel] = arr[oldLabel] - 1; //原标签减1,不影响最后arr[3]的值
				if (newLabel == 3) {
					//window.g_data.boxes.splice(ii, 1); //OK：去掉这个box
					//不需要做任何操作，box[0]=3，就是新识别成删除的种子
				} else {
					arr[newLabel] = arr[newLabel] + 1; //新标签加1
				}

				arr[3] = arr[0] + arr[1];

				setData(arr, '', false); //不替换

				setTimeout(showBoxesInCanvas, 100);

				document.querySelector("#boxesDiv").focus();
			}
			
			//清掉显示的box
			function removeBoxes()
			{						
				const $canvasImg = document.querySelector("#show");
				const $canvas = document.querySelector("#showBox");
				let ctx = $canvas.getContext("2d");
				ctx.clearRect(0, 0, $canvas.width, $canvas.height);
				ctx.clearRect(0, 0, $canvasImg.width, $canvasImg.height);
				
				console.log('removeBoxes')
				removeCurrentDiv();//清掉弹出的菜单
			}

			//在canvas上绘制boxes的调用
			function showBoxesInCanvas() {
				//console.log('showBoxesInCanvas.........');
				if (!window.g_data) {
					alert('没有数据');
					return;
				}
				removeCurrentDiv();

				const $canvasImg = document.querySelector("#show");

				const $canvas = document.querySelector("#showBox");
				let ctx = $canvas.getContext("2d");
				ctx.clearRect(0, 0, $canvas.width, $canvas.height);
				ctx.clearRect(0, 0, $canvasImg.width, $canvasImg.height);

				var rects = g_data.boxes;
				drawBoxes(ctx, 0, rects); //画出label=0的种子
				drawBoxes(ctx, 1, rects); //画出label=1的种子
				drawBoxes(ctx, 2, rects); //画出label=2的种子

				drawBoxes(ctx, 3, rects); //画出label=3的种子，被删除的种子

				if (document.querySelector("#labelNumber").checked == true)
					labelSeedNumbers(ctx);
			}

			//在canvas上显示div以及 绑定弹出菜单
			function doShowDiv(evt) {
				//console.log('doShowDiv.....');
				if (!window.g_data) {
					console.log('没有数据');
					return;
				}
				const $canvas = document.querySelector("#showBox");
				var rect = $canvas.getBoundingClientRect();

				if (isMobileDevice(true) == true) {
					var clientXX = evt.originalEvent.touches[0].clientX; //evt.changedTouches[0].clientX;
					var clientYY = evt.originalEvent.touches[0].clientY; //evt.changedTouches[0].clientY;
				} else {
					var clientXX = evt.clientX;
					var clientYY = evt.clientY;
				}

				x = (clientXX - rect.left) * ($canvas.width / rect.width);
				y = (clientYY - rect.top) * ($canvas.height / rect.height);

				//console.log('x=', x, '\ty=', y);
				//console.log('xxx=', evt.clientX - rect.left, '\tyyy=', evt.clientY - rect.top);

				var rects = g_data.boxes;
				let ratioX = rect.width / $canvas.width;
				let ratioY = rect.height / $canvas.height;

				for (let i in rects) {
					let box = rects[i]
					if (x <= box[4] && x >= box[2] && y <= box[5] && y >= box[3]) {
						if (window.saveDiv) {
							let ii = window.saveDiv.getAttribute('my_index');
							if (ii == i)
								return; //说明还在显示中
						}
						showSeedMaskDiv(box, ratioX, ratioY, i, $canvas);

						return;
					}
				}
				console.log('no click.........');
			}
			//在canvas上显示半透明层，提供下拉菜单的弹出
			function showSeedMaskDiv(box, ratioX, ratioY, ii, $canvas) {
				console.log('showSeedMaskDiv.....');
				let colors = ['red', 'blue', 'black'];
				let div = document.createElement('a');

				let ww = 3;
				let dd = 1;
				if (window.devicePixelRatio) //返回设备的DPR
					dd = window.devicePixelRatio;

				div.style.left = (box[2] * ratioX - ww) + "px";
				div.style.top = (box[3] * ratioY - ww) + "px";
				div.style.width = ((box[4] - box[2] + 1) * ratioX + ww) + "px";
				div.style.height = ((box[5] - box[3] + 1) * ratioY + ww) + "px";

				//console.log('showSeedMaskDiv___x=', div.style.left, '\ty=', div.style.top,
				//      '\twidth=', div.style.width, '\theight=', div.style.height);

				div.className = 'floatBox';
				div.style.borderColor = colors[box[0]];
				div.setAttribute('data-toggle', 'dropdown');
				div.setAttribute('my_index', ii);
				div.setAttribute('my_label', box[0]);

				$($canvas.parentNode).find('a[data-toggle]').remove(); //删除全部a

				div.onclick = function() {
					window.saveDiv = this;
					console.log('....in div.onclick');
				};
				$canvas.parentNode.appendChild(div);
			}

			function removeCurrentDiv() { //删除当前激活的mask
				if (window.saveDiv) {
					$(window.saveDiv).remove(); //最后删除					
				}
				window.saveDiv = null;
			}

			//查询是PC端还是移动端
			function isMobileDevice(bShow) {
				var sUserAgent = navigator.userAgent.toLowerCase();
				var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
				var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
				var bIsMidp = sUserAgent.match(/midp/i) == "midp";
				var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
				var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
				var bIsAndroid = sUserAgent.match(/android/i) == "android";
				var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
				var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
				if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
					if (bShow == true)
						console.log('移动端');
					return true; // 移动设备
				} else {
					if (bShow == true)
						console.log('PC端');
					return false; // PC
				}
			}

			//画出 矩形框
			function drawBoxes(ctx, label, rects) {
				let colors = ['red', 'blue', 'yellow', '#999999'];

				ctx.beginPath();
				ctx.lineWidth = "3";
				ctx.strokeStyle = colors[label];

				for (let box of rects) {
					if (box[0] == label)
						ctx.rect(box[2], box[3], box[4] - box[2], box[5] - box[3]);
				}
				ctx.stroke();
			}

			function labelSeedNumbers(ctx) {
				//console.log('labelSeedNumbers........')
				if (!window.g_data) {
					console.log('没有数据');
					return;
				}
				if (!window.g_data.sorted) {
					window.g_data.boxes.sort(function(a, b) {
						if (a[2] != b[2]) return a[3] - b[3];
						else return a[2] - b[2];
					});
					console.log('排序成功...')
					window.g_data.sorted = true;
				}

				var rects = g_data.boxes;

				ctx.font = "47px Times New Romans";
				ctx.fillStyle = 'blue';

				for (let i in rects) {
					box = rects[i];
					let dd = box[4] - box[2]
					ctx.fillText(String(Number(i) + 1), box[2], box[3] - 10)
				}
			}
		</script>
		<script>
			//主要是页面交互的代码
			function copyToClipboard() {
				let main = document.querySelector("#result");
				let health = main.querySelector("#health").value;
				let oneleaf = main.querySelector("#oneleaf").value;
				let partial = main.querySelector("#partial").value;
				let seeds = main.querySelector("#seeds").value;
				let oInput = main.querySelector("#copy_data");

				let res = '发芽种子检测数量：' + health;
				//res += '\n单叶种子数量：' + oneleaf;
				//res += '\n不确定种子数量：' + partial;
				oInput.value = res;

				oInput.select(); //选择对象
				document.execCommand("Copy"); //执行浏览器复制命令
				bootbox.alert({
					title: "提示",
					message: "复制成功！",
					size: 'small'
				});
			}

			function handleTakePhoto(e) {
				let arr = [0, 0, 0, 0];
				setData(arr, '', true);

				// 读取照片
				if (this.files && this.files[0]) {
					const fileData = this.files[0],
						fileReader = new FileReader();
					// 转化为base64
					fileReader.readAsDataURL(fileData);

					fileReader.onload = (e) => {
						changePhotoSize(fileReader.result).catch(e => {})
					};
				}
			}

			//准备再canvas中调用绘图
			function changePhotoSize(imgData) {
				const $canvas = document.querySelector("#show"),
					context = $canvas.getContext("2d"),
					image = new Image();

				image.src = imgData;
				

				let $canvasBox = document.querySelector("#showBox");

				return new Promise((resolve, reject) => {
					console.log('2222222');
					image.onload = function() {
						let divWidth = document.querySelector('#main').offsetWidth;

						$canvas.setAttribute("width", this.width + "px");
						$canvas.setAttribute("height", this.height + "px");

						$canvasBox.setAttribute("width", this.width + "px");
						$canvasBox.setAttribute("height", this.height + "px");

						let ctx = $canvasBox.getContext("2d");

						ctx.clearRect(0, 0, this.width, this.height);
						context.drawImage(this, 0, 0, this.width, this.height);

						resolve($canvas.toDataURL());

						$('#spinner').hide();
						//window.imgSize = [this.width, this.height];
						console.log(this.width, this.height);
					};
					image.onerror = (e) => {
						reject(e);
					};
				});
			}

			//提取4个输入框的数据
			function getInputDataArray() {
				let arr = new Array(4);
				let $div = document.querySelector('#result');
				arr[0] = Number($div.querySelector('#health').value);
				arr[1] = Number($div.querySelector('#oneleaf').value);
				arr[2] = Number($div.querySelector('#partial').value);
				arr[3] = Number($div.querySelector('#seeds').value);
				return arr;
			}

			function showData(data) {
				let arr = [Number(data.stat.health), Number(data.stat.oneleaf),
					Number(data.stat.partial), Number(data.stat.seeds)
				];

				$("#result div.input-group span.font-weight-bold").each(function(index, dom) {
					dom.innerText = arr[index];
				});

				setData(arr, data.fileImageWebPath, false);

				document.querySelector('#msgResult').innerText = data.statusText;
			}
			//设置输入框的数字显示
			function setData(arr, href, replaceImg) {
				let $div = document.querySelector('#result');

				$div.querySelector('#health').value = arr[0];
				$div.querySelector('#oneleaf').value = arr[1];
				$div.querySelector('#partial').value = arr[2];
				$div.querySelector('#seeds').value = arr[3];

				if (replaceImg == true)
					if ($div.querySelector('#showImg').style.display != 'none')
						$div.querySelector('#showImg').src = href;

				$jqs = $("#result input[inputmode='decimal']");
				$jqs.each(function(index, dom) {
					$(dom).val(arr[index]).trigger('change');
				});

				try { //设置数值颜色显示
					$jqs.each(function(index, dom) {
						let inValue = dom.value;
						let orValue = $(dom).parent().find('div.input-group-prepend span').text();
						orValue = Number(orValue);
						if (inValue == orValue) {
							dom.style.color = 'black';
						} else if (inValue > orValue) {
							dom.style.color = 'red';
						} else {
							dom.style.color = 'blue';
						}
					});
				} catch (e) {
					console.log(e);
				}
			}

			function showImageSrcInCanvas(url) {
				var img = new Image();

				img.crossOrigin = "anonymous";
				img.src = url;
				//console.log('showImageSrcInCanvas.........', url);				
				return new Promise((resolve, reject) => {
					img.onload = function() {
						console.log('showImageSrcInCanvas onload.........', url);

						let $canvas = document.querySelector("#show");
						let $canvasBox = document.querySelector("#showBox");

						let context = $canvas.getContext("2d");
						let ctx = $canvasBox.getContext("2d");

						context.clearRect(0, 0, $canvas.width, $canvas.height);

						$canvas.setAttribute("width", this.width + "px");
						$canvas.setAttribute("height", this.height + "px");

						$canvasBox.setAttribute("width", this.width + "px");
						$canvasBox.setAttribute("height", this.height + "px");

						context.drawImage(this, 0, 0, this.width, this.height);
						ctx.drawImage(this, 0, 0, this.width, this.height);
						resolve($canvas.toDataURL());
					};
					img.onerror = (e) => {
						console.log('error in showImageSrcInCanvas', e);
						reject(e);
					};
				});
			}
		</script>
		<button type="button" class="btn btn-primary" id="showDialog" data-toggle="modal" data-target="#myModal"
			style="display:none">
			打开模态框
		</button>
		<div class="modal fade" id="myModal">
			<div class="modal-dialog  modal-dialog-centered">
				<div class="modal-content">
					<div class="modal-header">
						<h4 class="modal-title">检测成果</h4>
						<button type="button" class="close" data-dismiss="modal">&times;</button>
					</div>
					<div class="modal-body">
						种子图片检测结果成功！
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
					</div>
				</div>
			</div>
		</div>


		<script src="{% static 'js/bootstrap-input-spinner.js' %}"></script>
		<script src="{% static 'js/bootbox.min.js' %}"></script>
		<script src="{% static 'js/showinput.js' %}"></script>

		<script>
		
		
			$("input[type='number']").inputSpinner();			
			
			$("#result input[inputmode='decimal']").each(function(index, dom) {
				dom.style.paddingLeft = "4 px !important";
				dom.style.paddingRight = "4 px !important";
				
				let div = document.createElement('div');
				div.className = "input-group-prepend";

				let span = document.createElement('span');
				span.className = 'font-weight-bold input-group-text';
				span.style.backgroundColor = 'white';
				span.style.minWidth = '3rem';
				span.style.textAlign = 'right';
				span.innerText = '0';
				if (index == 0)
					span.style.color = 'red';
				else if (index == 1)
					span.style.color = 'blue';
				else
					span.style.color = 'black';
				
				div.appendChild(span)
				dom.parentNode.appendChild(div);
			});
			//$('form > div.input-group > div.input-group').css('width', '75%')
		</script>

	</body>

</html>
